package com.sfexpress.mycatweb.monitor.mock;

//import org.hyperic.sigar.CpuInfo;
import org.hyperic.sigar.CpuPerc;
import org.hyperic.sigar.Mem;
import org.hyperic.sigar.NetInterfaceConfig;
import org.hyperic.sigar.NetInterfaceStat;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.sfexpress.mycatweb.entity.monitor.NetStat;

@Component
@Scope("singleton")
public class SigarMonitor {
	
	private Sigar sigar = new Sigar();
	
	public CpuPerc getCpuInfo() throws SigarException {
		return sigar.getCpuPerc();
	}
	
	public Mem getMemoryInfo() throws SigarException {
		return sigar.getMem();
	}
	
	public NetStat[] getNetworkInfo() throws SigarException {
		String[] ifList = sigar.getNetInterfaceList();
		NetStat[] netInfos = new NetStat[ifList.length];
		for(int i = 0; i < ifList.length; i++) {
			String name = ifList[i];
			NetInterfaceConfig netConfig = sigar.getNetInterfaceConfig(name);
			netConfig.getAddress();
			NetInterfaceStat netStat = sigar.getNetInterfaceStat(name);
			long txBytes = netStat.getTxBytes(); // 发送的字节总数
			long rxBytes = netStat.getRxBytes(); // 接收的字节总数
			NetStat netInfo = new NetStat();
			netInfo.setName(netConfig.getName());
			netInfo.setIpAddr(netConfig.getAddress());
			netInfo.setTxBytes(txBytes);
			netInfo.setRxBytes(rxBytes);
			netInfos[i] = netInfo;
		}
		return netInfos;
	}
	
	public NetStat getNetworkInfo(String ipAddress) throws SigarException {
		String[] ifList = sigar.getNetInterfaceList();
		for(int i = 0; i < ifList.length; i++) {
			String name = ifList[i];
			NetInterfaceConfig netConfig = sigar.getNetInterfaceConfig(name);
			NetInterfaceStat netStat = sigar.getNetInterfaceStat(name);
			if(netConfig.getAddress().equals(ipAddress)) {
				long txBytes = netStat.getTxBytes(); // 发送的字节总数
				long rxBytes = netStat.getRxBytes(); // 接收的字节总数
				NetStat netInfo = new NetStat();
				netInfo.setName(netConfig.getName());
				netInfo.setIpAddr(netConfig.getAddress());
				netInfo.setTxBytes(txBytes);
				netInfo.setRxBytes(rxBytes);
				return netInfo;
			}
		}
		return null;
	}
}
